package cn.tedu._06article.controller;

import cn.tedu._06article.base.response.JsonResult;
import cn.tedu._06article.base.response.StatusCode;
import cn.tedu._06article.mapper.UserMapper;
import cn.tedu._06article.pojo.dto.ArticleParam;
import cn.tedu._06article.pojo.dto.ArticleUid;
import cn.tedu._06article.pojo.dto.UsernamePa;
import cn.tedu._06article.pojo.vo.ArticleVO;
import cn.tedu._06article.pojo.vo.UserVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.sql.rowset.JdbcRowSet;

@Slf4j
@RequestMapping ("v1/user/")
@RestController
@Tag(name = "用户模块")
public class UserController {
    @Autowired
    private UserMapper mapper;
    @PostMapping("login")
    @Operation(description = "登录")
    @ApiOperationSupport(order = 10)
    public JsonResult login(@RequestBody UsernamePa up,HttpSession session)
    {
        UserVO uvo =mapper.userLogin(up);
        if(uvo==null)
            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
        session.setAttribute("user",uvo);
        return JsonResult.ok(uvo);
    }

    @PostMapping("punish")
    @Operation(description = "发布文章")
    @ApiOperationSupport(order = 20)
    public JsonResult punish(@RequestBody @Validated ArticleParam param,HttpSession session)
    {
        UserVO uvo=(UserVO) session.getAttribute("user");

        Long userId=uvo.getUserId();
        if(param.getTitle()==null||param.getContent()==null)
            return new JsonResult(StatusCode.THROWABLE_ERROR);
        ArticleUid articleUid = new ArticleUid();
        BeanUtils.copyProperties(param, articleUid);
        articleUid.setUserId(userId);
        mapper.addArticle(articleUid);

        return JsonResult.ok();
    }

    @PostMapping("selectArticle")
    @Operation(description = "查询文章")
    @ApiOperationSupport(order = 30)
    public JsonResult selectArticle(@Range(min = 1L,max = 100L,message = "输入id在1-100之间") Long articleId)
    {
        if(articleId<1||articleId>100)
            return new JsonResult(StatusCode.THROWABLE_ERROR);

        ArticleVO avo = mapper.select(articleId);
        return JsonResult.ok(avo);
    }
}
